import React, { useEffect, useRef, useState } from "react";
import dayjs, { Dayjs } from "dayjs";
import { Form, Input, Button, Select, message, DatePicker } from "antd";
import { IDish } from "@/interface/dish";
import api from "@/fetch";

import "./index.less";

const { Option } = Select;

const DishList: React.FC<{
  isAdd: boolean;
  menuId?: string;
  menuData?: IDish;
  addSuccess?: () => void;
  editSuccess?: () => void;
}> = (props) => {
  const { isAdd, menuData = null } = props;
  const [form] = Form.useForm<IDish>();
  const [isShow, setIsShow] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const cacheDish = useRef<IDish>({
    menuName: "",
    schoolId: "",
    menuDay: dayjs(),
    dishList: [],
  });

  useEffect(() => {
    if (!isAdd) {
      form.setFieldsValue(menuData);
    }
  }, []);

  useEffect(() => {
    if (!isAdd) {
      form.setFieldsValue(menuData);
    }
  }, [menuData]);

  const onFinish = async (values: IDish) => {
    console.log(values);

    const isLess =
      cacheDish.current.dishList?.length !== 0 &&
      cacheDish.current.dishList?.some(
        (dish) =>
          dish?.dishName === "" ||
          dish?.dishName === undefined ||
          dish?.mealSectionType === undefined,
      );

    if (isLess && !values.dishList) {
      message.error("请检查菜品信息是否完整");
      return;
    }

    if (isAdd) {
      values.menuDay = (values.menuDay as Dayjs).format("YYYY-MM-DD");
      if (!values.dishList && cacheDish.current.dishList?.length === 0) {
        message.error("请添加至少一道菜品");
        return;
      }
    }

    const params = values;
    if (!isAdd) {
      values.menuId = menuData.menuId;
    }

    if (!values.dishList) {
      values.dishList = cacheDish.current.dishList;
    }

    setIsLoading(true);
    try {
      await api.post(`/api/v1/admin/menu/${isAdd ? "save" : "update"}`, params);
      message.success(`${isAdd ? "添加" : "修改"}菜单成功`);
      form.resetFields();

      if (!isAdd) {
        props.editSuccess();
      }
      if (isAdd) {
        props.addSuccess();
      }
    } catch (error) {
      message.error(error?.message || `${isAdd ? "添加" : "修改"}菜单失败`);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="dishList-container">
      <Form form={form} onFinish={onFinish}>
        <Form.Item
          name="menuName"
          label="菜单名"
          rules={[{ required: true, message: "请输入菜单名" }]}
        >
          <Input className="custom-input" />
        </Form.Item>

        <Form.Item
          name="schoolId"
          label="学校id"
          rules={[{ required: true, message: "请输入学校id" }]}
        >
          <Input className="custom-input" />
        </Form.Item>

        {isAdd && (
          <Form.Item
            name="menuDay"
            label="菜单日期"
            rules={[{ required: true, message: "请输入菜单日期" }]}
          >
            <DatePicker
              style={{ width: "286px" }}
              placeholder="选择日期"
              format="YYYY-MM-DD"
            />
          </Form.Item>
        )}

        <div className="btn-center">
          <div className="btn-extend">
            {isShow ? (
              <div
                onClick={() => {
                  setIsShow(false);
                  cacheDish.current = form.getFieldsValue();
                }}
              >
                隐藏
              </div>
            ) : (
              <div onClick={() => setIsShow(true)}>
                展开{isAdd ? "增加" : "编辑"}菜品···
              </div>
            )}
          </div>
        </div>

        {isShow && (
          <Form.List name="dishList">
            {(fields, { add, remove }) => (
              <>
                {fields.map((field, index) => (
                  <div>
                    <Form.Item key={`${field.key}-${index}`}>
                      <Form.Item
                        {...field}
                        key={`${field.key}+${index}`}
                        name={[field.name, "dishName"]}
                        label="菜品名"
                        rules={[{ required: true, message: "请输入菜品名" }]}
                      >
                        <Input className="custom-input" />
                      </Form.Item>
                      <Form.Item
                        {...field}
                        key={`${field.key}/${index}`}
                        name={[field.name, "mealSectionType"]}
                        label="餐段类型"
                        rules={[{ required: true, message: "请选择餐段类型" }]}
                      >
                        <Select style={{ width: "286px" }}>
                          <Option value="0">早餐</Option>
                          <Option value="1">午餐</Option>
                          <Option value="2">晚餐</Option>
                        </Select>
                      </Form.Item>
                      <div className="btn-center">
                        <Button onClick={() => remove(field.name)}>删除</Button>
                      </div>
                    </Form.Item>
                  </div>
                ))}

                <Form.Item>
                  <div className="btn-center">
                    <Button onClick={() => add()}>添加菜品</Button>
                  </div>
                </Form.Item>
              </>
            )}
          </Form.List>
        )}

        <Form.Item>
          <div className="btn-center">
            <Button type="primary" htmlType="submit" loading={isLoading}>
              提交
            </Button>
          </div>
        </Form.Item>
      </Form>
    </div>
  );
};

export default DishList;
